<?php
declare (strict_types = 1);
/**
 * Created by PhpStorm.
 * User: broceli
 * Date: 19-9-9
 * Time: 下午2:20
 */
namespace app\middleware;

use think\Request;
use Closure;

class ResponseMiddleware{

    /**
     * 自定义返回json数据
     * 设置跨域
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next) {
        $response = $next($request);
        $response->contentType("application/json");
        $data = $response->getData();
        $data = is_array($data) ? json_encode($data) : $data;
        $response->data($data);
        $response->header([
            'Access-Control-Allow-Origin'=>'*',
            'Access-Control-Allow-Headers'=>'X-Requested-With, Content-Type, Accept, Origin, Authorization, ak, token',
            'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, PATCH, OPTIONS'
        ]);
        return $response;
    }
}
